//
//  NibLoadable.swift
//  huaya-jisu
//
//  Created by MK on 2021/7/30.
//  Copyright © 2021 taolang. All rights reserved.
//

import UIKit

protocol NibLoadable {
    
}

extension NibLoadable where Self : UIView {
    static func loadFromNib(_ nibName: String? = nil) -> Self {
       let loadName = nibName ?? "\(self)"
       
       // 检查 xib 文件是否存在
       guard let nibPath = Bundle.main.path(forResource: loadName, ofType: "nib") else {
           fatalError("Error: Nib file \(loadName) does not exist.")
       }
       
       guard let view = Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as? Self else {
           fatalError("Error: Could not load view from nib file \(loadName).")
       }
       
       return view
   }
}

extension NibLoadable where Self : UITableViewCell {
    static func loadFromNib(_ tableView : UITableView, nibName : String? = nil) -> Self {
        let loadName = nibName ?? "\(self)"
        var cell = tableView.dequeueReusableCell(withIdentifier: loadName)
        
        if cell == nil {
            // 检查 xib 文件是否存在
            if let nibPath = Bundle.main.path(forResource: loadName, ofType: "nib") {
                let nib = UINib(nibName: loadName, bundle: nil)
                if let nibObjects = nib.instantiate(withOwner: nil, options: nil) as? [UITableViewCell],
                   !nibObjects.isEmpty {
                    cell = nibObjects.first
                    if cell == nil {
                        print("Error: The first object in nib \(loadName) is not a UITableViewCell")
                    }
                } else {
                    print("Error: No objects found in nib \(loadName)")
                }
            } else {
//                print("Error: Nib file \(loadName) does not exist at path \(String(describing: nibPath))")
            }

        }
        return cell as! Self
    }
}

extension NibLoadable where Self : UITableViewCell {
    static func mk_cellByNib(_ tableView: UITableView, nibName: String? = nil) -> Self {
        let loadName = nibName ?? "\(self)"
        
        // 尝试从重用队列中获取单元格
        if let cell = tableView.dequeueReusableCell(withIdentifier: loadName) as? Self {
            return cell
        }
        
        // 检查 xib 文件是否存在
        if Bundle.main.path(forResource: loadName, ofType: "nib") == nil {
            fatalError("Error: Nib file \(loadName) does not exist.")
        }
        
        // 尝试从 xib 文件中加载单元格
        let nib = UINib(nibName: loadName, bundle: nil)
        if let nibObjects = nib.instantiate(withOwner: nil, options: nil) as? [UITableViewCell],
           let cell = nibObjects.first as? Self {
            return cell
        } else {
            // 创建一个默认的单元格
            let defaultCell = UITableViewCell(style: .default, reuseIdentifier: loadName)
            defaultCell.textLabel?.text = "默认单元格" // 设置默认内容
            return defaultCell as! Self
        }
    }
}
